<?php
namespace app\admin\validate;
use think\Validate;
use think\facade\Db;

class KeywordsCheck extends Validate
{
    protected $rule = [
        'title'       => 'require|checkUnique',
        'id'          => 'require',
    ];

    protected $message = [
        'title.require'       => '关键字名称不能为空',
        'title.checkUnique'   => '同样的关键字名称已经存在',
        'id.require'          => '缺少更新条件',
    ];

    protected $scene = [
        'add'   => ['title'],
        'edit' => ['id','title']
    ];

    //自定义验证规则
    protected function checkUnique($value,$rule,$data)
    {  
        if(isset($data['id'])){
            $unique =Db::name('keywords')->where([['id','<>',$data['id']],['title','=',$value],['status','>=',0]])->value('id');
        }else{
            $unique =Db::name('keywords')->where([['title','=',$value],['status','>=',0]])->value('id');
        }
       
        if($unique) {
            return false;
        }else{
            return true;
        }
    }

}